/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package puertocom;

import gnu.io.CommPortIdentifier;
import java.io.*;
import java.util.Enumeration;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

/**
 *
 * @author Marcelo
 */
public class FrmChat extends javax.swing.JFrame {

    /**
     * Creates new form FrmChat
     */
    public FrmChat() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtChat = new javax.swing.JTextArea();
        txtMsg = new javax.swing.JTextField();
        cmdEnviar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cmdConnect = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtNickname = new javax.swing.JTextField();
        cmdArchivo = new javax.swing.JButton();
        cmdDesconectar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat usando Puerto Serie");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        txtChat.setColumns(20);
        txtChat.setEditable(false);
        txtChat.setLineWrap(true);
        txtChat.setRows(5);
        txtChat.setEnabled(false);
        jScrollPane1.setViewportView(txtChat);

        txtMsg.setEnabled(false);
        txtMsg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMsgKeyTyped(evt);
            }
        });

        cmdEnviar.setText("Enviar");
        cmdEnviar.setEnabled(false);
        cmdEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdEnviarActionPerformed(evt);
            }
        });

        jLabel1.setText("Mensaje:");

        txtPort.setText("COM5");

        jLabel2.setText("Puerto:");

        cmdConnect.setText("Conectar");
        cmdConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdConnectActionPerformed(evt);
            }
        });

        jLabel3.setText("Alias:");

        txtNickname.setText("Usuario");

        cmdArchivo.setText("Archivo");
        cmdArchivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdArchivoActionPerformed(evt);
            }
        });

        cmdDesconectar.setText("Desconectar");
        cmdDesconectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdDesconectarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtMsg)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdEnviar))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdConnect)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdDesconectar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNickname, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdArchivo)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(cmdConnect)
                    .addComponent(jLabel3)
                    .addComponent(txtNickname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdArchivo)
                    .addComponent(cmdDesconectar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMsg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdEnviar)
                    .addComponent(jLabel1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    PuertoCOM puertoCom = null;
    
    private void cmdConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdConnectActionPerformed
        // TODO add your handling code here:
        ImplProtocolo.frmChat = this;
        puertoCom = new PuertoCOM();
        try {
            puertoCom.connect(txtPort.getText());
            txtNickname.setEnabled(false);
            txtMsg.setEnabled(true);
            txtChat.setEnabled(true);
            txtPort.setEnabled(false);
            cmdEnviar.setEnabled(true);
            cmdConnect.setEnabled(false);
            cmdDesconectar.setEnabled(true);
            txtMsg.requestFocus();
        } catch (Exception ex) {
            Logger.getLogger(FrmChat.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_cmdConnectActionPerformed

    public void addMessage(String msg)
    {
        txtChat.setText( txtChat.getText() + msg + "\n" );
        txtChat.select( txtChat.getText().length() , txtChat.getText().length());
    }
    private void sendTypedMessage()
    {
        String msg = txtMsg.getText();
        if (msg.length() == 0) return;

        msg = txtNickname.getText() + ": " + msg;
        Emisor.sendMessage( msg );  
        addMessage( msg );
        txtMsg.setText("");
        txtMsg.requestFocus();
    }
    private void cmdEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdEnviarActionPerformed
        // TODO add your handling code here:
        if (txtMsg.isEnabled())
            sendTypedMessage();
        
    }//GEN-LAST:event_cmdEnviarActionPerformed

    private void txtMsgKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMsgKeyTyped
        // TODO add your handling code here:
        if (evt.getKeyChar() == '\n')
        {
            sendTypedMessage();
        }
    }//GEN-LAST:event_txtMsgKeyTyped

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        Random random = new Random();
        int n = random.nextInt(100);
        txtNickname.setText( txtNickname.getText() + n ); 
    }//GEN-LAST:event_formWindowOpened

    public void desconexion()
    {
        Receptor.continuarLectura = false;
        addMessage("El otro usuario se ha desconectado.");
        
        desconectar();
    }
    
    public void iniciaRecepcion(long tam, String nomArchivo)
    {
        cmdEnviar.setEnabled(false);
        addMessage("Recibiendo: " + nomArchivo + " ("+ tam +" bytes)");
    }
    
    int oldPercent = 0;
    public void recibido(int transferidos, int total) 
    {
        int porcentaje = (int)transferidos*100/total;
        if (porcentaje > 0 && porcentaje % 10 == 0 && porcentaje != 100 && porcentaje != oldPercent)
        {
            addMessage("Transferido " + porcentaje + "%");
            oldPercent = porcentaje;
        }
    }
    
    private void cmdArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdArchivoActionPerformed

        String archivo = "";
        String nomArchivo = "";
        
        JFileChooser chooser = new JFileChooser();
        int r = chooser.showOpenDialog(this);
        if (r == JFileChooser.APPROVE_OPTION)
        {
            archivo = chooser.getSelectedFile().getAbsolutePath();
            nomArchivo = chooser.getSelectedFile().getName();
            
            System.out.println("Transfiriendo: " + archivo);
            addMessage("Transfiriendo: " + archivo);
        }
        else
            return;

        if (archivo == null || archivo.length() == 0)
            return;
        //String archivo = "C:\\xampplite\\passwords.rar";
        //String nomArchivo = "passwords.rar";
        
        long tamArchivo = 0;
        
        InputStream is = null;
        File arch = new File(archivo);
        tamArchivo = arch.length();
        
        cmdEnviar.setEnabled(false);
        
        Emisor.send("FILE " + tamArchivo + " " + nomArchivo + "\n");
        try {
            is = new FileInputStream( archivo );

            //Envio envio = new Envio(this, is);
            //envio.start();
            
            long tt = tamArchivo % 3000;
            
            byte[] buffer = new byte[1024];  
            try {
                
                long c=0;
                //for (int n; (n = is.read()) != -1;)
                for (int n; (n = is.read(buffer)) != -1;)
                {
                    c++;
                    for (int i=0;i<n;i++)
                    {
                        Emisor.send( buffer[i] );
                    }
                    //Emisor.send(buffer,0,n);
                    /*
                    try {

                        if ( c % 3000 == 0 && c < tamArchivo - 3000)
                        {
                            Thread.sleep(10);
                        }
                        
                    } catch (InterruptedException ex) {
                        Logger.getLogger(FrmChat.class.getName()).log(Level.SEVERE, null, ex);
                    }*/
                }
                /*
                for (int n; (n = is.read(buffer)) != -1; )   
                {

                    Emisor.send(buffer, 0, n);
                    //Emisor.send(n);
                }*/
              
                addMessage("Envio completado");
            } catch (IOException ex) {
                Logger.getLogger(FrmChat.class.getName()).log(Level.SEVERE, null, ex);
            }
                    
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FrmChat.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(FrmChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        cmdEnviar.setEnabled(true);
    }//GEN-LAST:event_cmdArchivoActionPerformed

    private void cmdDesconectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdDesconectarActionPerformed
        // TODO add your handling code here:
         botonDesconectar();
    }//GEN-LAST:event_cmdDesconectarActionPerformed

    void botonDesconectar()
    {
         Emisor.send( "DISCONNECT\n" );           
         desconectar();
         addMessage("Te has desconectado");        
    }
    
    public void transferenciaCompleta()
    {
        cmdEnviar.setEnabled(true);
        addMessage("Transferencia completa");
    }
    
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        botonDesconectar();
    }//GEN-LAST:event_formWindowClosing

    private void desconectar()
    {
        txtPort.setEnabled(true);
        cmdConnect.setEnabled(true);
        cmdDesconectar.setEnabled(false);
        txtMsg.setEnabled(false);
        txtChat.setEnabled(false);
        txtNickname.setEnabled(true);
        
        if (puertoCom != null)
            puertoCom.close();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FrmChat frm = new FrmChat();
                frm.setLocationRelativeTo(null);
                frm.setVisible(true);
                                
            Enumeration ports = CommPortIdentifier.getPortIdentifiers();  
          
            while(ports.hasMoreElements())  
                System.out.println(((CommPortIdentifier)ports.nextElement()).getName());                        
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdArchivo;
    private javax.swing.JButton cmdConnect;
    private javax.swing.JButton cmdDesconectar;
    private javax.swing.JButton cmdEnviar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtChat;
    private javax.swing.JTextField txtMsg;
    private javax.swing.JTextField txtNickname;
    private javax.swing.JTextField txtPort;
    // End of variables declaration//GEN-END:variables
}
